// 引入接口文件
import { getMember, downLoadFile } from './activityDetailServ'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { download } from 'utils/util'

// 初始默认状态
const defultState = {
  loading: false,
  btnLoading: false,
  //表格数据
  exportLoading:false,
  listData: [],
  tableData: {dataSource: []},
  detailData: {},//详情数据
  queryCondition: {status: '', code: ''},//查询数据
  id: '',//id
  activeKey: '',//选中的tabs
  activityId: ''
}

// 声明module
const tmpModule = {
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup ({dispatch, history}) {
      history.listen(({pathname, query}) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          // 执行业务操作
          dispatch({type: 'updateStore', payload: {activityId: query.id}})
          dispatch({type: 'queryInfo', payload: {activityId: query.id}}) // end dispatch
        } // end if
      }) // end listen
    },
  },
  
  // 方法列表
  effects: {
    // 查询记录
    * queryInfo ({payload}, {put, call, select}) {
      try {
        const {data, resultCode, resultMsg} = yield call(getMember, parse(payload))
        yield put({ // 调用reducers中方法，把新数据与状态机数据合并更新
          type: 'updateStore', // 方法名，也可以调用effects中的方法
          payload: {
            listData: data.data,
            detailData: data
          }
        })
      } catch (e) {
        console.error(e)
      }
    },
    * downLoad ({payload}, {put, call, select}) {
      try {
        yield put({type: 'updateStore', payload: {exportLoading: true}})
        const {data, success, msg} = yield call(downLoadFile, parse(payload))
        yield put({type: 'updateStore', payload: {exportLoading: false}})
        if (success) {
          let url = data || ''
          if (url) {
            download(url)
          }
          yield put({type: 'updateStore', payload: {url: data}})
        } else {
          message.error(`${msg}`)
        }
      } catch (e) {
        console.error(e)
      }
    },
  },
  
  // 存入状态机
  reducers: {
    updateStore (preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
